package com.tilas.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tilas.mapper.ClazzMapper;
import com.tilas.pojo.Clazz;
import com.tilas.pojo.ClazzQueryParam;
import com.tilas.pojo.PageResult;
import com.tilas.service.ClazzService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class ClazzSerivceImpl implements ClazzService {


    @Autowired
    private ClazzMapper clazzMapper;


    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        //1.设置分页参数
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());

        //2.执行查询
        List<Clazz> clazzList = clazzMapper.list(clazzQueryParam);

        for (int i = 0; i < clazzList.size(); i++) {
            LocalDate beginDate = clazzList.get(i).getBeginDate();
            LocalDate endDate = clazzList.get(i).getEndDate();
            LocalDate nowDate = LocalDate.now();
            if ((nowDate.isAfter(beginDate) || nowDate.equals(beginDate)) && (nowDate.isBefore(endDate)||  nowDate.equals(endDate))) {
                clazzList.get(i).setStatus("已开班");
            }else if (nowDate.isBefore(beginDate)) {
                clazzList.get(i).setStatus("未开班");
            }else if (nowDate.isAfter(endDate)){
                clazzList.get(i).setStatus("已结班");
            }
        }
        //3.封装分页结果
        Page<Clazz> p = (Page<Clazz>) clazzList;


        return new PageResult<>(p.getTotal(),p.getResult());
    }

    @Override
    public void delete(Integer id) {
        clazzMapper.delete(id);
    }

    @Override
    public void add(Clazz clazz) {
        //1.修改时间
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.add(clazz);
    }

    @Override
    public Clazz findById(Integer id) {
        Clazz clazz = clazzMapper.findById(id);
        return clazz;
    }

    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }
}
